#-*- coding:utf-8 -*-
from icalendar import Calendar, Event
import pytz
import datetime
import hashlib
import tkinter
import tkinter.messagebox
import webbrowser

#支持json
import json

#用于解决null等关键字未定义的问题
null = None
false = False
true = True


def sha1(data):
    return hashlib.sha1(data.encode('utf-8')).hexdigest()

# 在这里修改你开学第一周时间
yourstarttime = '2021-09-06'

def get_course_date(first_day_date_str, course_in_day_of_week, which_week):  # 返回上课的日期
    first_day_date = datetime.datetime.strptime(
        first_day_date_str, r'%Y-%m-%d')
    return first_day_date + datetime.timedelta(days=(which_week - 1) * 7 + (course_in_day_of_week - 1))


def get_course_take_time(course_time):  # 返回上课时间
    course_time_table = {'12': [[8, 0, 0], [9, 35, 0]],
                         '34': [[10, 5, 0], [11, 40, 0]],
                         '14': [[8, 0, 0], [11, 40, 0]],

                         '56': [[14, 0, 0], [15, 35, 0]],
                         '78': [[15, 55, 0], [17, 30, 0]],
                         '58': [[14, 0, 0], [17, 30, 0]],
                         
                         '910': [[19, 0, 0], [20, 35, 0]],
                         '911':[[19, 0, 0], [21, 25, 0]]}
    return course_time_table[course_time][0], course_time_table[course_time][1]


def main():
    time_zone = pytz.timezone('Asia/Shanghai')
    first_day_date_str = yourstarttime
    schedule_json = yourjson
    if schedule_json == -1:
        print('yourjson 没填')
        exit(1)
    name = schedule_json['studentTableVm']['name']
    class_name = schedule_json['studentTableVm']['adminclass']
    courses = schedule_json['studentTableVm']['activities']
    calendar = Calendar()
    calendar.add('prodid', '-//My calendar product//mxm.dk//')
    calendar.add('version', '2.0')
    for course in courses:
        course_in_day_of_week = int(course['weekday'])  # 课程在星期几
        # course_take_weeks = get_course_take_weeks(course['allWeek'])
        course_take_weeks = list(course['weekIndexes'])
        # print(("{}{}".format(course['startUnit'],course['endUnit'])))
        course_begin_time, course_end_time = get_course_take_time("{}{}".format(course['startUnit'],course['endUnit']))
        for week in course_take_weeks:
            course_date = get_course_date(first_day_date_str, course_in_day_of_week, week)
            event = Event()
            event.add('summary', course['courseName'])
            event.add('dtstart',
                      datetime.datetime(course_date.year, course_date.month, course_date.day, course_begin_time[0],
                                        course_begin_time[1], course_begin_time[2], tzinfo=time_zone))
            event.add('dtend',
                      datetime.datetime(course_date.year, course_date.month, course_date.day, course_end_time[0],
                                        course_end_time[1], course_end_time[2], tzinfo=time_zone))
            event.add('dtstamp',
                      datetime.datetime(course_date.year, course_date.month, course_date.day, course_begin_time[0],
                                        course_begin_time[1], course_begin_time[2], tzinfo=time_zone))
            event.add('location', course['room'])
            calendar.add_component(event)
    output_file_name = '{} - {}.ics'.format(class_name, name)
    output_file = open(output_file_name, 'wb')
    output_file.write(calendar.to_ical())
    output_file.close()
    print('Success write your calendar to', output_file_name)
    tkinter.messagebox.showinfo('提示', '没啥大毛病的话，文件应该已经生成在程序目录下了！') 


def start_work():
    global yourjson
    get_text = e.get()
    if (get_text != "") and get_text.startswith('{\"studentTableVm\"') and get_text.endswith('}}'):
        yourjson = json.loads(e.get())
        main()               
    else:
        tkinter.messagebox.showinfo('提示',"请输入正确的JSON，确保以studentTableVm字符开头！")
        return      
    

if __name__ == '__main__':
    yourjson = None
    webbrowser.open('https://portal-ui.paas.jmu.edu.cn/')
    root = tkinter.Tk()
    root.title("JSON2ICS工具   By.HAIYANG")
    root.geometry('500x200')
    root.resizable(width=False, height=False)

    e = tkinter.Entry(root, show=None, bd=5)
    e.place(x=1,y=11,height=120,width=498)

    b = tkinter.Button(root,command = start_work,text="确认")
    b.place(x=200,y=155,height = 45,width = 100)
    

    tkinter.messagebox.showinfo('声明','此程序用于简单生成ICS文件，由GnaixEuy作者改版而来，感谢大佬代码！\n如果首次运行程序输入框中无光标，请点一次确认即可')
    root.mainloop()
    
